import { defineStore } from 'pinia'
import type { GoodInfo } from '@/interface/good'
import type { UserListingQuery, UserListingInfo, ManagerListingQuery,ManagerListingInfo } from '@/interface/listing'
import { queryListingByUid, queryListingByYearMonth, queryListingByOfficeId } from '@/api/listing'
import { allPrice } from '@/api/price'


interface goodsState {
  listing: GoodInfo[],
  userListing: UserListingInfo[],
  managerListing: ManagerListingInfo[]
}

export const useGoodsStore = defineStore({
  id: 'goodsStore',
  state: (): goodsState => ({
    listing: sessionStorage.getItem('listing') ? JSON.parse(sessionStorage.listing) : [],
    userListing: [],
    managerListing: []
  }),
  getters: {

  },
  actions: {
    changeListing(payload: GoodInfo) {
      const listing = this.listing
      const { id, num } = payload
      // 如果不包含
      if (!listing.map(item => item.id).includes(id) && payload.num != 0) {
        // ! antd inputnumber input输入会触发两次所以必须加上 num!=0 条件
        listing.push(payload)
      } else {
        for (let idx in listing) {
          if (listing[idx].id === id) {
            // 包含的情况下 数量为0
            if (!num) listing.splice(parseInt(idx), 1)
            else listing[idx].num = num
            break
          }
        }
      }
      const listingStr = JSON.stringify(listing)
      sessionStorage.setItem('listing', listingStr)
    },

    getListingPriceInfo(payLoad: GoodInfo[]) {
      const goodFormat = payLoad.map(item => ({
        num: item.num,
        price: item.c_price
      }))
      return new Promise(async (resolve, reject) => {
        const { data: { msg, data } } = await allPrice(goodFormat)
        if (msg === 'ok') {
          resolve(data)
        } else {
          reject(new Error('出错了！'))
        }
      })
    },

    clearListing() {
      this.listing = []
      sessionStorage.removeItem('listing')
    },

    async getUserListingByUid(userId: string | number) {
      const { data: { data, msg } } = await queryListingByUid(userId)

      if (msg === 'ok') {
        this.userListing = data
      } else {
        return new Error('出错了！')
      }
    },
    async getUserListingByYearMonth(data: UserListingQuery) {
      const { data: { data: res, msg } } = await queryListingByYearMonth(data)
      if (msg === 'ok') {
        this.userListing = res
      } else {
        return new Error('出错了！')
      }
    },

    async getManagerListingByOfficeId(oid: string | number) {
      const { data: { data } } = await queryListingByOfficeId(oid)
      this.managerListing = data
    },

    async getManagerListingByYearMonth(data: ManagerListingQuery) {
      const { data: { data: res, msg } } = await queryListingByYearMonth(data)
      if (msg === 'ok') {
        this.managerListing = res
      } else {
        return new Error('出错了！')
      }
    },

  }
})